package org.beetl.json;

import java.util.ArrayList;
import java.util.List;

import org.beetl.json.action.FormatAction;
import org.beetl.json.action.IgnoreAction;
import org.beetl.json.action.KeyChangeAction;
import org.beetl.json.loc.AttributeLocation;
import org.beetl.json.loc.ClassLocation;
import org.beetl.json.loc.TypeLocation;

/** 序列化规则解析
 * @author xiandafu
 *
 */
public class PolicyParser {
	
	public Location init(Class cls){
		Location root = new ClassLocation();
		
		Json json = (Json)cls.getAnnotation(Json.class);
		if(json!=null){
			String policy = json.policy();
			List<Location> list = parse(policy);
			
			 root.children.addAll(list);
		}
		
		
		return root;
		
	}
	
	protected static List<Location>  parse(String policy){
		
		String[] strs = policy.split(",");
		 List<Location>  list = new ArrayList<Location> ();
		for(String str:strs){
			String[] temp = str.split(":");
			String loc = temp[0],act=temp[1];
			LocationAction action = null;
			Location location = null;
			//先处理位置=====
			if(loc.startsWith("~")){
				//某个指令
				String cmd = loc.substring(1);
				if(cmd.equals("f")){
					//浮点
					location = new TypeLocation(cmd);
					
				}else if(cmd.equals("d")){
					location = new TypeLocation(cmd);
				}
				else{
					throw new UnsupportedOperationException();
				}
			}else{
				//暂时忽略user.wife:i这种属性
				String attrName = loc;
				location = new AttributeLocation (attrName);
				
			}
			
			//处理action=====		
			if(act.startsWith("i")){
				//忽略操作
				action = new IgnoreAction();
				
			}else if(act.startsWith("f")){
				//格式化操作 f'yyyy-MM-dd'
				String format = act.substring(2,act.length()-1);
				action = new FormatAction(format);
			}else if(act.startsWith("k")){
				//修改keyName
				String targetName = act.substring(2,act.length()-1);
				action = new KeyChangeAction(targetName);
				
			}
			
			location.setAction(action);	
			list.add(location);
			
			
			
		}
		
		return list;
		
		
	}
	
	
}
